package com.yiming.shiro.controller;

import com.yiming.shiro.controller.vo.UserPassVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@Slf4j
public class LoginController {

    @PostMapping("/login")
    public String login(@RequestBody UserPassVO userPassVO) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()) {
            return "success";
        }
        AuthenticationToken authenticationToken = new UsernamePasswordToken(userPassVO.getUser(), userPassVO.getPassword());
        try {
            currentUser.login(authenticationToken);
            return "success";
        } catch (AuthenticationException e) {
            log.error("login failed.");
        }
        return "failed";
    }

    @GetMapping(value = "/logout")
    public String logout(HttpServletResponse response) {
        //这里一定要使用shiro退出方式，否则session失效
        SecurityUtils.getSubject().logout();
        return "logout success";
    }

}
